//
//  TravelNoteViewController.m
//  HappyTrip
//
//  Created by dlios on 15-3-25.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "TravelNoteViewController.h"
#import "UIImageView+AFNetworking.h"
#import "HotTravel.h"
#import "Waypoints.h"
#import "WaypointsCell.h"
#import "PhotoViewController.h"

//数据库
#import "NoteCollect.h"
#import "DateBaseHandler.h"
#import "RecView.h"

@interface TravelNoteViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *daysArr;
@property (nonatomic, retain) NSMutableArray *waypointsArr;
// 数据库
@property (nonatomic, retain) NoteCollect *noteCollect;
//@property (nonatomic, retain) RecView *recView;

@end

@implementation TravelNoteViewController
- (void)dealloc
{
    [_waypointsArr release];
    [_noteCollect release];
    [_tableView release];
    [_daysArr release];
    [_name release];
    [_Id release];
    [_first_day release];
    [_day_count release];
    [_user release];
    [_recommendations release];
    [_start_point release];
    [super dealloc];
}
- (void)getCollect
{
    //收藏
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] init];
    [self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStylePlain];
    [self.navigationItem.rightBarButtonItem setTarget:self];
    [self.navigationItem.rightBarButtonItem setAction:@selector(barAction:)];
//    NSArray *arr = [[DateBaseHandler shareInstance] selectAll];
//    NSMutableArray *nameArr = [NSMutableArray array];
//    for (NSString *name in arr) {
//        [nameArr addObject:name];
//    }
//    if ([nameArr containsObject:self.noteCollect.name]) {
//        [self.navigationItem.rightBarButtonItem setTitle:@"已收藏"];
//    }else{
//        [self.navigationItem.rightBarButtonItem setTitle:@"收藏"];
//    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
//    self.tabBarController.selectedIndex = 0;
//    [self.navigationController setNavigationBarHidden:YES animated:NO];// 隐藏导航栏
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemAction:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    
    [self handleData];
    [self getCollect];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 边缘回弹效果
    self.tableView.bounces = NO;
    [self.view addSubview:self.tableView];
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeAction:)];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.tableView addGestureRecognizer:swipe];
    [swipe release];
    [_tableView release];
    
    // 菊花
    self.MBProgress = [[MBProgressHUD alloc] initWithView:self.view];
    self.MBProgress.labelText = @"加载中...";
    self.MBProgress.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:self.MBProgress];
    [self.MBProgress show:YES];
    [_MBProgress release];
    
    [self.tableView registerClass:[WaypointsCell class] forCellReuseIdentifier:@"reuse"];
    
    
}

// tebleView的协议方法  返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    HotTravel *hotTravel = [self.daysArr objectAtIndex:section];
    NSArray *array = hotTravel.waypoints;
    return array.count;
}
// 创建cell 并赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WaypointsCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"reuse"];
    HotTravel *hotTravel = [self.daysArr objectAtIndex:indexPath.section];
    NSDictionary *dic = [hotTravel.waypoints objectAtIndex:indexPath.row];
    cell.waypointsDic = dic;
    NSLog(@"00000000%ld", indexPath.row);
    cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
    return cell;
        
}
// 返回每个cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HotTravel *hotTravel = [self.daysArr objectAtIndex:indexPath.section];
    NSDictionary *wayDic = [hotTravel.waypoints objectAtIndex:indexPath.row];
    
    NSString *str = [wayDic objectForKey:@"text"];
//    NSLog(@"------___+++++%@", str);
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
    CGRect rect = [str boundingRectWithSize:CGSizeMake(self.tableView.frame.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    NSDictionary *photoDic = [wayDic objectForKey:@"photo_info"];
    NSString *photoStr = [wayDic objectForKey:@"photo"];
    NSLog(@"0+++____+++++%@, ", photoDic);
    if (0 != photoStr.length) {
        if ([wayDic objectForKey:@"photo_info"] == [NSNull null]) {
            return rect.size.height + (self.tableView.frame.size.width - 20) / 2 + 40 + 10;
        }else{
            CGFloat h = [[photoDic objectForKey:@"h"] floatValue];
            CGFloat w = [[photoDic objectForKey:@"w"] floatValue];
            CGFloat heigth = (self.tableView.frame.size.width - 20) * h / w;
            return rect.size.height + heigth + 40 + 10;
        }
    }else{
        return rect.size.height + 40 + 10;
    }
//    return 600;
    
    
    
    
}

// tableView的分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return self.daysArr.count;
}

// cell 的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{   NSArray *array = [[self.daysArr objectAtIndex:indexPath.section] waypoints];
    if ([[[array objectAtIndex:indexPath.row] objectForKey:@"photo"] length] != 0) {
//        NSLog(@"--------%ld", indexPath.row);
        PhotoViewController *photVC = [[PhotoViewController alloc] init];
        photVC.hidesBottomBarWhenPushed = YES;
        photVC.array = self.daysArr;
        // 偏移量传值
        self.page = 0;
//        for (NSInteger i = 0; i <= indexPath.section; i++) {
//            // 计算点击处是第几个cell 从0开始计算
//            if (indexPath.section != 0) {
//                self.page += [[[self.daysArr objectAtIndex:(indexPath.section - 1)] waypoints] count] + indexPath.row;
//                // 判断如果当没有图片的时候计数减 1.
//                for (NSDictionary *dic in [[self.daysArr objectAtIndex:(indexPath.section - 1)] waypoints]) {
//                    if (0 == [[dic objectForKey:@"photo"] length]) {
//                        self.page = self.page - 1;
//                    }
//                }
//            }else{
//                self.page = indexPath.row;
//                for (NSInteger i = 0; i <= indexPath.row; i++) {
//                    if (0 == [[[[[self.daysArr objectAtIndex:indexPath.section] waypoints] objectAtIndex:i] objectForKey:@"photo"] length]) {
//                        self.page = self.page - 1;
//                    }
//                }
//            }
//        }
        for (NSInteger i = 0; i <= indexPath.section; i++) {
            if (i < indexPath.section) {
                self.page = self.page + [[[self.daysArr objectAtIndex:i] waypoints] count];
                NSLog(@"waypoints.count %ld", [[[self.daysArr objectAtIndex:i] waypoints] count]);
                for (NSDictionary *dic in [[self.daysArr objectAtIndex:i] waypoints]) {
                    if (0 == [[dic objectForKey:@"photo"] length]) {
                        self.page = self.page - 1;
                    }
                }
            }else{
                self.page = self.page + indexPath.row;
                for (NSInteger i = 0; i <= indexPath.row; i++) {
                    if (0 == [[[[[self.daysArr objectAtIndex:indexPath.section] waypoints] objectAtIndex:i] objectForKey:@"photo"] length]) {
                        self.page = self.page - 1;
                    }
                }
            }
            
        }
        NSLog(@"indexPath.row %ld", indexPath.row);
        NSLog(@"section===== %ld", indexPath.section);
        NSLog(@"self.page% ld", self.page);
        photVC.page = self.page;
        //    NSLog(@"photo   ......%@", array);
//        NSLog(@" indexPath.row  %ld", indexPath.row);
        [self.navigationController pushViewController:photVC animated:YES];
        [photVC release];
    }
}


// 判断每个分区section的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
// 分区section显示的内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    HotTravel *hotTravel = [self.daysArr objectAtIndex:section];
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor colorWithRed:185.0 / 255 green:220.0 / 255 blue:199.0 / 255 alpha:1.0f];

    label.textAlignment = NSTextAlignmentLeft;
    NSString *year = [hotTravel.date substringWithRange:NSMakeRange(0, 4)];
    NSString *month = [hotTravel.date substringWithRange:NSMakeRange(5, 2)];
    NSString *day = [hotTravel.date substringWithRange:NSMakeRange(8, 2)];
    label.text = [NSString stringWithFormat:@"  第%ld天 %@年%@月%@日",(section + 1), year, month, day];
    label.textColor = [UIColor groupTableViewBackgroundColor];
    return [label autorelease];
}
// 返回按钮
- (void)leftBarButtonItemAction:(UIBarButtonItem *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 数据请求
- (void)handleData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/", self.transmitId];
//    NSLog(@"%@```````````````@", self.transmitId);
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTripDestination", docPath, [urlStr hash]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
//        NSLog(@"%@", path);
        self.title = [responseObject objectForKey:@"name"];
        self.Id = [responseObject objectForKey:@"id"];
//        // 数据库
        self.noteCollect = [[NoteCollect alloc] initWithDictionary:responseObject];
        
        self.daysArr = [NSMutableArray array];
        self.waypointsArr = [NSMutableArray array];
        NSArray *daysArray = [responseObject objectForKey:@"days"];
        for (NSDictionary *dic in daysArray) {
            HotTravel *hotTravel = [[HotTravel alloc] initWithDictionary:dic];
            [self.daysArr addObject:hotTravel];
            [hotTravel release];
        }
        [self.tableView reloadData];
        // 数据库判断 显示是否收藏
        NSArray *arr = [[DateBaseHandler shareInstance] selectAll];
        NSMutableArray *nameArr = [NSMutableArray array];
        for (NoteCollect *name in arr) {
            [nameArr addObject:[name name]];
            NSLog(@"%@", nameArr);
        }
        if ([nameArr containsObject:self.noteCollect.name]) {
            NSLog(@"%@---------%@", self.noteCollect.name, self.title);
            [self.navigationItem.rightBarButtonItem setTitle:@"已收藏"];
        }else{
            NSLog(@"%@-----++++----%@", self.noteCollect.name, self.title);
            [self.navigationItem.rightBarButtonItem setTitle:@"收藏"];
        }

        [self.MBProgress removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        //self.collectionViewMutableArr = [resultID objectForKey:@"elements"];
        NSLog(@"result: %@", resultID);
        [self.MBProgress removeFromSuperview];
    }];
}
- (void)barAction:(UIBarButtonItem *)bar
{
    DateBaseHandler *db = [DateBaseHandler shareInstance];
    [db creataTable];
    self.noteCollect = [[NoteCollect alloc] init];
    self.noteCollect.idNumber = self.Id;
    self.noteCollect.name = self.title;
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"收藏"]) {
        self.navigationItem.rightBarButtonItem.title = @"已收藏";
        [db inserNoteCollect:self.noteCollect];
//        NSLog(@"note.name %ld", self.noteCollect.idNumber);
    }else{
        self.navigationItem.rightBarButtonItem.title = @"收藏";
        [db deleteNoteCollecrt:self.noteCollect];
    }
    [_noteCollect release];
}

- (void)swipeAction:(UISwipeGestureRecognizer *)swipe
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
//    self.navigationController.navigationBarHidden = YES;
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    //    self.tabBarController.tabBar.hidden = NO;
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
